import guid from './guid'
import signature from './signature'

const base_url = 'http://localhost:5010/api/v1/'
const header = {
  'content-type': 'application/json',//'application/x-www-form-urlencoded',
  'Authorization': "Bearer " + wx.getStorageSync("token"),
  'secret':signature.secret,
  'x-requestid':guid.newGuid(),
}
/**
 * function: 根据需求处理请求参数：添加固定参数配置等
 * @param 请求参数
 */
function dealParams(params) {
  console.log("请求参数:", params)
  return params;
}
/**
 * function: 封装网络请求
 * @url URL地址
 * @params 请求参数
 * @method 请求方式：GET/POST/
 */
function request(url, params, method) {
  console.log('请求url：' + url);
  wx.showLoading({
    title: "正在加载中...",
  })
  console.log("请求头：", header)
  /********签名参数**********/
    //时间戳
    let timestamp = Date.parse(new Date()) / 1000
    //随机数
    let nonce = Math.floor(Math.random()*1000)
    let signaturevalue = signature.signal(timestamp,nonce)
    let parameter_url = signature.createurl(timestamp,nonce,signaturevalue)
  /*************************/
  return new Promise((resolve,reject) =>{
    wx.request({
      url: base_url + url + parameter_url,
      data: dealParams(params),
      method: method,
      header: header,
      success: function(res) {
        wx.hideLoading();
        if (res.data) {
          /** start 根据需求 接口的返回状态码进行处理 */
          if (res.statusCode == 200) {
            resolve(res.data); //request success
          } else {
            reject(res.data.message); //request failed
          }
          /** end 处理结束*/
        }else{
          reject("");
        }
      },
      fail: function(error) {
        reject(error);; //failure for other reasons
      }
    })
  })
}
/**
 * get请求
 */
function get(data) {
  return request(data.url, data.params, "GET");
}
/**
 * POST请求
 */
function post(data) {
  return request(data.url, data.params, "POST");
}
/**
 * DELETE请求
 */
function del(data) {
  return request(data.url, data.params, "DELETE");
}
/**
 * PUT请求
 */
function put(url, params) {
  return request(data.url, data.params, "PUT");
}
// 通过module.exports方式提供给外部调用
module.exports = {
  postRequest: post,
  getRequest: get,
  deleteRequest:del,
  putRequest:put,
}